 
package net.jforum.view.forum;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.context.RequestContext;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.ForumDAO;
import net.jforum.dao.ModerationLogDAO;
import net.jforum.dao.TopicDAO;
import net.jforum.entities.ModerationLog;
import net.jforum.entities.Topic;
import net.jforum.entities.User;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.PostRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.repository.SummaryRepository;
import net.jforum.repository.TopicRepository;
import net.jforum.security.SecurityConstants;
import net.jforum.util.CommonUtil;
import net.jforum.util.I18n;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.forum.common.ForumCommon;

import org.apache.log4j.Logger;

import freemarker.template.SimpleHash;
/**
 * @author Rafael Steil
 * @version $Id: ModerationHelper.java,v 1.43 2007/09/10 14:56:38 rafaelsteil Exp $
 */
public class ModerationHelper 
{
	private static Logger logger = Logger.getLogger(ModerationHelper.class);
	
	public static final int SUCCESS = 1;
	public static final int FAILURE = 2;
	public static final int IGNORE = 3;
	
	public int doModeration(String returnUrl)
	{
		int status = FAILURE;

		if (SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION)) {
			// Deleting topics
			RequestContext request = JForumExecutionContext.getRequest();
			
			if (request.getParameter("topicRemove") != null) {
				if (SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_POST_REMOVE)) {
					this.removeTopics();
					
					status = SUCCESS;
				}
			}
			else if (request.getParameter("topicMove") != null) {
				if (SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_TOPIC_MOVE)) {
					this.moveTopics();
					
					status = IGNORE;
				}
			}
			else if (request.getParameter("topicLock") != null) {
				if (SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_TOPIC_LOCK_UNLOCK)) {
					this.lockUnlockTopics(Topic.STATUS_LOCKED);
					
					status = SUCCESS;
				}
			}
			else if (request.getParameter("topicUnlock") != null) {
				if (SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_TOPIC_LOCK_UNLOCK)) {
					this.lockUnlockTopics(Topic.STATUS_UNLOCKED);
					
					status = SUCCESS;
				}
			}
			//置酷
			else if(request.getParameter("topicExcellent")!=null){ 
				if (SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
				 this.makeUnmakeTopicExcellent(Topic.GRADE_Ku);
				 status = SUCCESS;
				}
			}
			//置顶					
			else if(request.getParameter("topicSticky")!=null){
				 this.updateTopicType(Topic.TYPE_STICKY);
				 status = SUCCESS;
			}
			//取消置酷
			else if(request.getParameter("topicExcellentCancel")!=null){
				 
				if (SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
				 this.makeUnmakeTopicExcellent(Topic.GRADE_NORMAL);
				 status = SUCCESS;
				}
			
			}
			//取消置顶或公告
			else if(request.getParameter("topicStickyCancel")!=null){
				if (SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
					 this.updateTopicType(Topic.TYPE_NORMAL);
					 status = SUCCESS;
					}
			}
			//公告设置
			else if(request.getParameter("topicAnnouce")!=null){
				if (SecurityRepository.canAccess(SecurityConstants.PERM_CREATE_STICKY_ANNOUNCEMENT_TOPICS)) {
					 this.updateTopicType(Topic.TYPE_ANNOUNCE);
					 status = SUCCESS;
					}
			}
 
			
		}

		if (status == ModerationHelper.FAILURE) {
			this.denied();
		}
		else if (status == ModerationHelper.SUCCESS && returnUrl != null) {
			JForumExecutionContext.setRedirect(returnUrl);
		}
		
		return status;
	}
	
	// 置酷
	public void makeUnmakeTopicExcellent(int topicGrade){
		String[] topics = JForumExecutionContext.getRequest().getParameterValues("topic_id");
		
		if (topics != null && topics.length > 0) {
			int[] ids = new int[topics.length];
			 
//			ModerationLog log = this.buildModerationLogFromRequest();

			for (int i = 0; i < topics.length; i++) {
				ids[i] = Integer.parseInt(topics[i]);
//				log.setTopicId(ids[i]);
//				this.saveModerationLog(log);
			}
			 
			 DataAccessDriver.getInstance().newTopicDAO().updateTopicGrade(ids, topicGrade);
			
			// Clear the cache
			Topic t = DataAccessDriver.getInstance().newTopicDAO().selectById(ids[0]);
			TopicRepository.clearCache(t.getForumId());
			
			//update 虚拟总论坛 cache
			TopicRepository.loadAllTopicsForCache();
			//update 最近主题
			TopicRepository.loadMostRecentTopics();
			//更新 KuTopics缓存；
			TopicRepository.loadKuTopics();
//			TopicRepository.loadKuTopicsCount();
			int cacheSize = SystemGlobals
			.getIntValue(ConfigKeys.TOPIC_BY_PUBLISH_TIME_CACHE_SIZE);
			TopicRepository.loadTopicsByPublishTime(0, cacheSize);
		}
	}
    
	
	//置顶，也可以公告
	public void updateTopicType(int type){
		String[] topics = JForumExecutionContext.getRequest().getParameterValues("topic_id");
		
		if (topics != null && topics.length > 0) {
			int[] ids = new int[topics.length];
			 
//			ModerationLog log = this.buildModerationLogFromRequest();

			for (int i = 0; i < topics.length; i++) {
				ids[i] = Integer.parseInt(topics[i]);
//				log.setTopicId(ids[i]);
//				this.saveModerationLog(log);
			}
			 
			 DataAccessDriver.getInstance().newTopicDAO().updateTopicType(ids, type);
			
			// Clear the cache
			Topic t = DataAccessDriver.getInstance().newTopicDAO().selectById(ids[0]);
			TopicRepository.clearCache(t.getForumId());
			
			//update 虚拟总论坛 cache
			TopicRepository.loadAllTopicsForCache();
			TopicRepository.loadKuTopics();
			TopicRepository.loadMostRecentTopics();
			int cacheSize = SystemGlobals
			.getIntValue(ConfigKeys.TOPIC_BY_PUBLISH_TIME_CACHE_SIZE);
			TopicRepository.loadTopicsByPublishTime(0, cacheSize);
		}
	}
 
	public void saveModerationLog(ModerationLog log)
	{
		ModerationLogDAO dao = DataAccessDriver.getInstance().newModerationLogDAO();
		dao.add(log);
	}
	
	public ModerationLog buildModerationLogFromRequest()
	{
		RequestContext request = JForumExecutionContext.getRequest();
		
		ModerationLog log = new ModerationLog();
		
		User user = new User();
		user.setId(SessionFacade.getUserSession().getUserId());
		log.setUser(user);
		
		log.setDescription(request.getParameter("log_description"));
		log.setOriginalMessage(request.getParameter("log_original_message"));
		log.setType(request.getIntParameter("log_type"));
		
		if (request.getParameter("post_id") != null) {
			log.setPostId(request.getIntParameter("post_id"));
		}
		
		String[] values = request.getParameterValues("topic_id");
		
		if (values != null && values.length == 1) {
			log.setTopicId(request.getIntParameter("topic_id"));
		}
		
		return log;
	}
	
	public int doModeration() 
	{
		return this.doModeration(null);
	}
	
	private void removeTopics()
	{
		String[] topics = JForumExecutionContext.getRequest().getParameterValues("topic_id");
		
		List forumsList = new ArrayList();
		TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
		
		List topicsToDelete = new ArrayList();
		
		if (topics != null && topics.length > 0) {
			ModerationLog log = this.buildModerationLogFromRequest();
			
			for (int i = 0; i < topics.length; i++) {
				Topic t = tm.selectRaw(Integer.parseInt(topics[i]));
				
				log.setTopicId(t.getId());
				log.setPosterUser(t.getPostedBy());
				
				this.saveModerationLog(log);
				
				if (!forumsList.contains(new Integer(t.getForumId()))) {
					forumsList.add(new Integer(t.getForumId()));
				}
				
				topicsToDelete.add(t);
				PostRepository.clearCache(t.getId());
				
				if(CommonUtil.isTopicPublishToday(t)){
					SummaryRepository.decreaseTodayTopicCountByForum(t.getForumId(), 1);
					SummaryRepository.decreaseCounttAllNewTopicToday(1);
					
				}

			}
		 
			tm.deleteTopics(topicsToDelete, false);
			
			
			
			ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();
			TopicRepository.loadMostRecentTopics();
			//add by myself
			TopicRepository.loadTopicsCount();
			TopicRepository.loadAllTopicsForCache();
			TopicRepository.loadKuTopics();
			int cacheSize = SystemGlobals
			.getIntValue(ConfigKeys.TOPIC_BY_PUBLISH_TIME_CACHE_SIZE);
			TopicRepository.loadTopicsByPublishTime(0, cacheSize);
			
			// Reload changed forums
			for (Iterator iter = forumsList.iterator(); iter.hasNext(); ) {
				int forumId = ((Integer)iter.next()).intValue();

				TopicRepository.clearCache(forumId);
				
				int postId = fm.getMaxPostId(forumId);
				
				if (postId > -1) {
					fm.setLastPost(forumId, postId);
				}
				else {
					logger.warn("Could not find last post id for forum " + forumId);
				}
				
				ForumRepository.reloadForum(forumId);
				
			}
			

		}
	}
	
	private void lockUnlockTopics(int status)
	{
		String[] topics = JForumExecutionContext.getRequest().getParameterValues("topic_id");
		
		if (topics != null && topics.length > 0) {
			int[] ids = new int[topics.length];
			
			ModerationLog log = this.buildModerationLogFromRequest();

			for (int i = 0; i < topics.length; i++) {
				ids[i] = Integer.parseInt(topics[i]);
				log.setTopicId(ids[i]);
				this.saveModerationLog(log);
			}
			
			DataAccessDriver.getInstance().newTopicDAO().lockUnlock(ids, status);
			
			// Clear the cache
			Topic t = DataAccessDriver.getInstance().newTopicDAO().selectById(ids[0]);
			TopicRepository.clearCache(t.getForumId());
			//add by myself
//			TopicRepository.loadTopicsCount();
			TopicRepository.loadAllTopicsForCache();
			TopicRepository.loadMostRecentTopics();
			TopicRepository.loadKuTopics();
			int cacheSize = SystemGlobals
			.getIntValue(ConfigKeys.TOPIC_BY_PUBLISH_TIME_CACHE_SIZE);
			TopicRepository.loadTopicsByPublishTime(0, cacheSize);
		}
	}
	
	private void moveTopics()
	{
		SimpleHash context = JForumExecutionContext.getTemplateContext();
		
		context.put("persistData", JForumExecutionContext.getRequest().getParameter("persistData"));
		context.put("allCategories", ForumCommon.getAllCategoriesAndForums(false));
		
		String[] topics = JForumExecutionContext.getRequest().getParameterValues("topic_id");
		
		if (topics.length > 0) {
			// If forum_id is null, get from the database
			String forumId = JForumExecutionContext.getRequest().getParameter("forum_id");
			
			if (forumId == null) {
				int topicId = Integer.parseInt(topics[0]);
				
				Topic topic = TopicRepository.getTopic(new Topic(topicId));
				
				if (topic == null) {
					topic = DataAccessDriver.getInstance().newTopicDAO().selectRaw(topicId);
				}
				
				forumId = Integer.toString(topic.getForumId());
			}
			
			context.put("forum_id", forumId);
			
			StringBuffer sb = new StringBuffer(128);
			
			for (int i = 0; i < topics.length - 1; i++) {
				sb.append(topics[i]).append(",");
			}
			
			sb.append(topics[topics.length - 1]);
			
			context.put("topics", sb.toString());
		}
	}
	
	public int moveTopicsSave(String successUrl)
	{
		int status = SUCCESS;
		
		if (!SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_TOPIC_MOVE)) {
			status = FAILURE;
		}
		else {
			RequestContext request = JForumExecutionContext.getRequest();
			String topics = request.getParameter("topics");
			
			if (topics != null) {
				int fromForumId = Integer.parseInt(request.getParameter("forum_id"));
				int toForumId = Integer.parseInt(request.getParameter("to_forum"));
				
				String[] topicList = topics.split(",");
				
				DataAccessDriver.getInstance().newForumDAO().moveTopics(topicList, fromForumId, toForumId);
				
				ModerationLog log = this.buildModerationLogFromRequest();
				
				for (int i = 0; i < topicList.length; i++) {
					int topicId = Integer.parseInt(topicList[i]);
					log.setTopicId(topicId);
					this.saveModerationLog(log);
				}

				ForumRepository.reloadForum(fromForumId);
				ForumRepository.reloadForum(toForumId);
				
				TopicRepository.clearCache(fromForumId);
				TopicRepository.clearCache(toForumId);
				
				SummaryRepository.decreaseTodayTopicCountByForum(fromForumId, topicList.length);
				SummaryRepository.increaseTodayTopicCountByForum(toForumId, topicList.length);
				
				TopicRepository.loadMostRecentTopics();
				TopicRepository.loadTopicsCount();
				TopicRepository.loadAllTopicsForCache();
				int cacheSize = SystemGlobals
				.getIntValue(ConfigKeys.TOPIC_BY_PUBLISH_TIME_CACHE_SIZE);
				TopicRepository.loadTopicsByPublishTime(0, cacheSize);

                
			}
		}
		
		if (status == FAILURE) {
			this.denied();
		}
		else {
			this.moderationDone(successUrl);
		}
		
		return status;
	}
	
	public String moderationDone(String redirectUrl)
	{
		JForumExecutionContext.getRequest().setAttribute("template", TemplateKeys.MODERATION_DONE);
		JForumExecutionContext.getTemplateContext().put("message", I18n.getMessage("Moderation.ModerationDone", new String[] { redirectUrl }));
		
		return TemplateKeys.MODERATION_DONE;
	}
	
	public void denied()
	{
		this.denied(I18n.getMessage("Moderation.Denied"));
	}
	
	public void denied(String message)
	{
		JForumExecutionContext.getRequest().setAttribute("template", TemplateKeys.MODERATION_DENIED);
		JForumExecutionContext.getTemplateContext().put("message", message);		
	}
}
